import WxValidate from "../../../../utils/wx-validate/WxValidate";
import Promise from '../../../../utils/es6-promise/es6-promise'
import regeneratorRuntime from '../../../../utils/regenerator-runtime/runtime'
const utils = require('../../../../utils/util.js');
const app=getApp();
Page({
  data: {
    iconSize: [20],
    iconColor: ['#f00'],
    iconType: ['cancel'],
    creditImgLimit:20,
    fundImgLimit:20,
    token:null,
    isUpdateUserInfo:false,
    form: {
      invite_code:null,
      wx_id:"",
      user_id:"",
      user_name:"",
      user_phone:"",
      user_age:"",
      hometown:"",
      work_address:"",
      education:"",
      marriage:"",
      company_nature: "",
      company_name: "",
      annual_income: "",
      is_social_security: "",
      is_accumulation_fund: "",
      now_work_time: "",
      is_legal_person: "",
      is_legal_partner: "",
      house_num: "",
      house_list: [],
      car_num: "",
      car_list: [],
      loan_num: "",
      loan_list: [],
      credit_card_num: "",
      credit_card_list: [],
      capital_bank: "",
      wages_bank: "",
      fund: "",
      disposable_money: "",
      loan_house_plan: "",
      apply_quota: "",
      refuse_record: "",
      other: "",
      pattern:"",
      senior_pic_list1:[],
      senior_pic_list2:[],
      senior_pic1:[],
      senior_pic2:[]
    },
    ageInfo: [],
    eduInfo: [],
    jobCompany: [],
    workTimeInfo: [],
    marriageInfo: ["未婚","已婚","离异"],
    statusType: ["否","是"],
    propertyInfo: ["0","1","2","3","4","5","6","7","8","9","10"],
    modeInfo: ["信用卡方案","信用贷方案","信贷全套方案"],
    uploadImageUrl:"/api/common/uploadImage",
    getInfoUrl:"/api/users/getInfo",
    getBaseDataUrl:"/api/common/getBaseData",
    formUrl:"/api/SeniorService/addSeniorApply",
    delImageUrl:"/api/common/delImage"
  },
  onLoad: async function(params) {
    wx.showLoading({
      title:"加载中..."
    })
    var code=params.code;
    console.log(code);
    this.setData({
      'form.invite_code':code
    })
    this.initValidate();
    console.log("onLoad");
    const token = await app.getToken();
    this.setData({
      token:token
    })
    var data=await this._getInfo();
    if(data.state){
      var info=data.data;
      this.setData({
        "form.user_name":info.uname,
        "form.user_phone":info.mobile,
        "form.user_id":info.user_id,
        isUpdateUserInfo:info.uname=="" && info.mobile==""
      })
    }
    /* 
    ageInfo: ["25岁以下","25-30岁","30-50岁","50岁-60岁","60岁以上"],
    eduInfo: ["大专及以下","本科","硕士及以上"],
    jobCompany: ["政府单位","国企事业单位","世界500强","上市公司","其他"],
    workTimeInfo: ["3个月以下","3-6个月","6个月-1年","1年以上"],
    */
    var baseData=await this._getBaseData();
    wx.hideLoading();
    if(baseData.state){
      var info=baseData.data;
      this.setData({
        ageInfo:info.user_age,
        eduInfo:info.education,
        jobCompany:info.company_nature,
        workTimeInfo:info.now_work_time
      })
    }
    else{
      wx.showToast({
        title:baseData.msg,
        icon:"none",
        duration:1000
      })
    }

    
    //console.log(this.WxValidate);
  },
  _getInfo:function(){
    var p = new Promise((resolve,reject)=>{
        //做一些异步操作
        app.request(this.data.getInfoUrl,{token:this.data.token},res=>{
          //console.log(res);
          var data=res.data;
          if(data.state){
            resolve({state:true,data:data.data});
          }
          else{
            resolve({state:false,msg:data.msg});          
          }
        },error=>{
          resolve({state:false,msg:"获取失败，请重试"});
        })
    });
    return p;
  },
  _getBaseData:function(){
    var p = new Promise((resolve,reject)=>{
        //做一些异步操作
        app.request(this.data.getBaseDataUrl,{token:this.data.token},res=>{
          //console.log(res);
          var data=res.data;
          if(data.state){
            resolve({state:true,data:data.data});
          }
          else{
            resolve({state:false,msg:data.msg});          
          }
        },error=>{
          resolve({state:false,msg:"获取失败，请重试"});
        })
    });
    return p;
  },
  initValidate() {
    // 验证字段的规则
    const rules = {
      wx_id: {
        required: true
      },
      user_name: {
        required: true,
        truename: true
      },
      user_phone: {
        required: true,
        tel:true
      },
      user_age: {
        required: true
      },
      hometown: {
        required: true
      },
      work_address: {
        required: true
      },
      education: {
        required: true
      },
      marriage: {
        required: true
      },
      company_nature: {
        required: true
      },
      company_name: {
        required: true
      },
      annual_income: {
        required: true,
        number:true
      },
      is_social_security: {
        required: true
      },
      is_accumulation_fund: {
        required: true
      },
      now_work_time: {
        required: true
      },
      is_legal_person: {
        required: true
      },
      is_legal_partner: {
        required: true
      },
      house_num: {
        required: true
      },
      car_num: {
        required: true
      },
      loan_num: {
        required: true
      },
      credit_card_num: {
        required: true
      },
      capital_bank: {
        required: true
      },
      wages_bank: {
        required: true
      },
      fund: {
        required: true
      },
      disposable_money: {
        required: true
      },
      loan_house_plan: {
        required: true
      },
      apply_quota: {
        required: true
      },
      refuse_record: {
        required: true
      },
      other: {
        required: true
      },
      pattern: {
        required: true
      }
    };

    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      wx_id: {
        required: "请输入微信ID"
      },
      user_name: {
        required: "请输入预约人姓名",
        truename: "姓名格式不正确"
      },
      user_phone: {
        required: "请输入手机号码",
        tel:"手机号码格式不正确"
      },
      user_age: {
        required: "请选择年龄"
      },
      hometown: {
        required: "请填写户籍"
      },
      work_address: {
        required: "请填写工作所在地"
      },
      education: {
        required: "请选择学历"
      },
      marriage: {
        required: "请选择婚姻状况"
      },
      company_nature: {
        required: "请选择工作单位性质"
      },
      company_name: {
        required: "请填写工作单位名称"
      },
      annual_income: {
        required: "请填写税后收入",
        number:"税后收入格式不正确"
      },
      is_social_security: {
        required: "请选择社保缴纳情况"
      },
      is_accumulation_fund: {
        required: "请选择公积金缴纳情况"
      },
      /* fund: {
        required: "请输入公积金月缴纳额",
        number:"公积金金额格式不正确"
      }, */
      now_work_time: {
        required: "请选择现单位工作时间"
      },
      is_legal_person: {
        required: "请选择公司法人信息"
      },
      is_legal_person: {
        required: "请选择公司股东信息"
      },
      house_num: {
        required: "请选择家庭房产情况"
      },
      car_num: {
        required: "请选择名下车辆情况"
      },
      loan_num: {
        required: "请选择信用贷情况"
      },
      credit_card_num: {
        required: "请选择信用卡分期情况"
      },
      capital_bank: {
        required: "请填写资金往来银行信息"
      },
      wages_bank: {
        required: "请填写代发工资银行信息"
      },
      fund: {
        required: "请填写金融资产信息"
      },
      disposable_money: {
        required: "请填写空闲资金信息"
      },
      loan_house_plan: {
        required: "请填写贷款购购房计划信息"
      },
      apply_quota: {
        required: "请填写想要申请的额度"
      },
      refuse_record: {
        required: "请填写申卡被拒记录"
      },
      other: {
        required: "请填写其他情况说明"
      },
      pattern: {
        required: "请选择定制模式"
      }
    };
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages);
  },
  submitForm:async function (e) {
    const params = e.detail.value;
    params.formId = e.detail.formId;
    params.invite_code = this.data.form.invite_code;
    console.log(params);
    //this._stringData(params,["house_list","car_list","loan_list","credit_card_list","senior_pic1","senior_pic2"]);
    //debugger;
    // 传入表单数据，调用验证方法
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0];
      this.showModal(error);
      return false;
    }
    var checkArrListType=this.checkArrList();
    if(checkArrListType){
      wx.showLoading({
        title:"提交中，请稍后..."
      })
      //debugger;
      this._stringData(params,["house_list","car_list","loan_list","credit_card_list","senior_pic1","senior_pic2"]);
      params.token=this.data.token;
      params.pattern=(params.pattern-0+1).toString();
      var result=await this._setForm(params);
      if(result.state){
        var func=function(){
          wx.hideLoading();
          this.showModal(result.msg,function(){
            wx.navigateBack({
              delta: 1
            })
          })
        }.bind(this)
        if(this.data.isUpdateUserInfo){
          var userInfo=await this._setUserInfo(params);
          func();
        }
        else func();
        
      }
      else{
        wx.hideLoading();
        this.showModal(result);
      }
    }
  },
  _setForm:function(params){
    var p = new Promise((resolve,reject)=>{
      //做一些异步操作   
        app.request(this.data.formUrl,params,res=>{
          //console.log(res);
          var data=res.data;
          if(data.state){
            resolve({state:true,msg:data.msg});
          }
          else{
            resolve({state:false,msg:data.msg});          
          }
        },error=>{
          resolve({state:false,msg:"提交失败，请重试"});
        })
    });
    return p;
  },
  _stringData:function(params,arr){
    var form=this.data.form;
    arr.forEach(function (item, index, array) {
      params[item]=form[item].length==0?"":JSON.stringify(form[item]);
    })
    return params;
  },
  _setUserInfo:function(params){
    var p = new Promise((resolve,reject)=>{
        //做一些异步操作
        app.request(this.data.setInfoUrl,{token:this.data.token,user_id:this.data.form.user_id,uname:params.user_name,mobile:params.user_phone},res=>{
          //console.log(res);
          var data=res.data;
          if(data.state){
            resolve({state:true,data:data.msg});
          }
          else{
            resolve({state:false,msg:data.msg});          
          }
        },error=>{
          resolve({state:false,msg:"提交失败，请重试"});
        })
    });
    return p;
  },
  showModal(error,cb) {
    wx.showModal({
      content: error.msg || error,
      showCancel: false,
      success(res) {
        if(cb) cb();
      }
    });
  },
  checkArrList:function(){
    var arr=['house_list','car_list','loan_list','credit_card_list'];
    var errorList=['家庭名下房产信息未填写完整','个人名下车产状况未填写完整','信用贷使用状况未填写完整','卡分期情况未填写完整'];
    var type=true;
    var errText;
    for(let index=0;index<arr.length;index++){
      var item=arr[index];
      var arrList=this.data.form[item];
      if(errText) break;
      if(arrList.length==0) continue;
      for(let i=0;i<arrList.length;i++){
        var item2=arrList[i];
        for(var j in item2){
          if(item2[j]=="") type=false;
        }
        if(!type) {
          errText=errorList[index];
          break;
        }
      }
    }
    if(errText) this.showModal(errText);
    return type;
  },
  pickerChange:function(e) {
    var name=e.target.dataset.name;
    var key = "form." + name;
    this.setData({
      [key]: e.detail.value
    });
    if(name=="house_num") this.changeHouseNumList(e.detail.value);
    if(name=="car_num") this.changeCarNumList(e.detail.value);
    if(name=="loan_num") this.changeLoanNumList(e.detail.value);
    if(name=="credit_card_num") this.changeCreditCardNumList(e.detail.value);
  },
  pickerJsonChange:function(e) {
    var name=e.target.dataset.name;
    var key = "form." + name;
    this.setData({
      [key]: e.detail.value
    });
  },
  changeHouseNumList:function(value){
    var propertyBase={
      city:"",
      host_value:"",
      loan_amount:"",
      loan_nature:"",
      repayment_quota:"",
      property_have:""
    };
    this.updateArrList(propertyBase,"house_list",value);
  },
  changeCarNumList:function(value){
    var carBase={
      naked_value:"",
      loan_amount:"",
      repayment_quota:""
    };
    this.updateArrList(carBase,"car_list",value);
  },
  changeLoanNumList:function(value){
    var loanBase={
      bank_name:"",
      quota:"",
      quota_userd:"",
      repayment_quota:""
    };
    this.updateArrList(loanBase,"loan_list",value);
  },
  changeCreditCardNumList:function(value){
    var cardBase={
      bank_name:"",
      quota:"",
      quota_userd:"",
      repayment_quota:""
    };
    this.updateArrList(cardBase,"credit_card_list",value);
  },
  updateArrList:function(baseArr,arr,value){
    var arrList=this.data.form[arr];
    if(value) {
      value=Number(value);
      if(value<arrList.length) arrList.splice(value,arrList.length-value);
      for(let i=0;i<value;i++){
        if(arrList[i]) continue;
        arrList[i]=JSON.parse(JSON.stringify(baseArr));
      }
    }
    else arrList=[];
    var key='form.'+arr;
    this.setData({
      [key]:arrList
    })
  },
  refreshArrList:function(e){
    var arr=e.target.dataset.arr;
    var name=e.target.dataset.name;
    var index=e.target.dataset.index-1;
    var key = "form."+arr+"["+index+"]." + name;
    this.setData({
      [key]:e.detail.value
    })
  },
  uploadImgs:function(e){
    var name=e.currentTarget.dataset.name;
    var kname=e.currentTarget.dataset.kname;
    var maxnum=e.currentTarget.dataset.maxnum;
    var that=this;
    wx.chooseImage({
      count: maxnum,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        wx.showLoading({title:"加载中..."});
        const tempFilePaths = res.tempFiles;
        var filesLen=0,fileIndex=0;
        for(let i in tempFilePaths){filesLen++};       
        tempFilePaths.forEach(function (item, index, array) {
          wx.getImageInfo({
            src: item.path,
            success(res) {
              console.log(res.width)
              console.log(res.height)
              wx.uploadFile({
                url: app.globalData.baseUrl+that.data.uploadImageUrl,
                filePath: item.path,
                name: 'pic',
                success(res) {
                  const data = JSON.parse(res.data);
                  if(data.state) that.updateImgList(name,kname,item.path,item.size,res.orientation,res.type,data.url);
                  fileIndex++;
                  if(fileIndex==filesLen){
                    wx.hideLoading();
                  }
                },
                fail:function(){
                  fileIndex++;
                  if(fileIndex==filesLen){
                    wx.hideLoading();
                  }
                }
              })
            }
          })
        })
      }
    })
  },
  updateImgList:function(name,kname,tempPath,size,orientation,type,url){
    var imgList=this.data.form[name].slice(0);
    var urlList=this.data.form[kname];
    var size=parseFloat(size/1024)>1024?parseFloat(size/1024/1024).toFixed(2)+"Mb":parseFloat(size/1024).toFixed(2)+"Kb";
    imgList.push({
      tempPath:tempPath,
      size:size,
      orientation:orientation,
      type:type,
      url:url
    })
    urlList.push(url);
    var key='form.'+name;
    var key2='form.'+kname;
    this.setData({
      [key]:imgList,
      [key2]:urlList
    })
  },
  delImage:function(e){
    var name=e.currentTarget.dataset.name;
    var kname=e.currentTarget.dataset.kname;
    var index=e.currentTarget.dataset.index;
    var data=this.data.form[name].slice(0);
    data.splice(index,1);
    var key="form."+name;
    var data2=this.data.form[kname];
    var url=data2.splice(index,1);
    var key2="form."+kname;
    this.setData({
      [key]:data,
      [key2]:data2
    })
    app.request(this.data.delImageUrl,{pic:url[0]},function(res){
      console.log(res);
    })
  }

});
